package com.epfresh.supplier.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.MarketPermissionUtil;
import com.epfresh.api.utils.Utils;
import com.epfresh.supplier.Listener.IndexIconOnClickListener;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.BookActivity;
import com.epfresh.supplier.activity.ChangePriceActivity;
import com.epfresh.supplier.activity.CustomerInfoActivity;
import com.epfresh.supplier.activity.GoodsStockActivity;
import com.epfresh.supplier.activity.H5OrderDetailActivity;
import com.epfresh.supplier.activity.JoinPrepareListActivity;
import com.epfresh.supplier.activity.JoinPriceActivity;
import com.epfresh.supplier.activity.MoreEvaluateActivity;
import com.epfresh.supplier.activity.MyCouponActivity;
import com.epfresh.supplier.activity.OfferListActivity;
import com.epfresh.supplier.activity.OrderMinusDetailActivity;
import com.epfresh.supplier.activity.OrderMinusListActivity;
import com.epfresh.supplier.activity.OrderMoreActivity;
import com.epfresh.supplier.activity.ProductActivity;
import com.epfresh.supplier.activity.StoreActivity;
import com.epfresh.supplier.activity.StoreEnsureAndOpenActivity;
import com.epfresh.supplier.activity.employ.EmployManageActivity;
import com.epfresh.supplier.activity.standingbook.DebtActivity;
import com.epfresh.supplier.activity.standingbook.StandingBookActivity;
import com.epfresh.supplier.adapter.HomePart1Adapter;
import com.epfresh.supplier.adapter.HomePart2Adapter;
import com.epfresh.supplier.adapter.HomePart3Adapter;
import com.epfresh.supplier.adapter.HomePartBottomAdapter;
import com.epfresh.supplier.adapter.HomePartTopAdapter;
import com.epfresh.supplier.adapter.HomePartTopSmallAdapter;
import com.epfresh.supplier.adapter.HomeTopPopAdapter;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.HomeNewEvenbus;
import com.epfresh.supplier.entity.HomeNewUpadteEvenbus;
import com.epfresh.supplier.entity.HomePart;
import com.epfresh.supplier.entity.MerChantInfo;
import com.epfresh.supplier.entity.MerchantMember;
import com.epfresh.supplier.entity.MineCertStatusEvenbus;
import com.epfresh.supplier.entity.OrderStoreDyn;
import com.epfresh.supplier.entity.ReceiptReponse;
import com.epfresh.supplier.entity.StaffInfo;
import com.epfresh.supplier.entity.WebTokenReponse;
import com.epfresh.supplier.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import multitype.OnRecyclerViewItemClickListener;

import static com.epfresh.supplier.widget.ViewVariable.HOME_ACTIVITY;

public class HomeNewFragment extends BaseFragment implements View.OnClickListener, AppBarLayout.OnOffsetChangedListener {
    private RefreshLayout mRefreshLayout;
    private TextView tvTitle;
    private RelativeLayout llTitle;
    private LinearLayout llMarketTitle, llTransactionTitle, llOnlineRetailersTitle;
    private View tvPopBg;
    private ImageView ivArrow;
    private RecyclerView rvTabTop, rvTabTopSmall, rvTab1, rvTab2, rvTab3, rvBottom;
    private HomePartTopAdapter homePartTopAdapter;
    private HomePartTopSmallAdapter homePartTopSmallAdapter;
    private HomePart1Adapter homePart1Adapter;
    private HomePart2Adapter homePart2Adapter;
    private HomePart3Adapter homePart3Adapter;
    private HomePartBottomAdapter homePartBottomAdapter;
    private Map<String, Integer> part1Permission = new HashMap<>();//市场服务权限列表
    private Map<String, Integer> part2Permission = new HashMap<>();//电子化交易权限列表
    private Map<String, Integer> part3Permission = new HashMap<>();//农批电商权限列表
    private List<HomePart> partTopList = new ArrayList<>();//常用
    private List<HomePart> part1List = new ArrayList<>();//市场服务
    private List<HomePart> part2List = new ArrayList<>();//电子化交易
    private List<HomePart> part3List = new ArrayList<>();//农批电商
    private boolean isOnclickPay = false;//有没有点击过缴费
    private List<OrderStoreDyn> mOrderStoreDyns = new ArrayList<>();
    private TextView tvOpenShop;//开网店
    private List<MerChantInfo> merChantInfoList = new ArrayList<>();
    private ListPopupWindow mListPop;
    private int pageNum = 0;
    private boolean last;
    private AppBarLayout appBar;
    /**
     * 大布局背景，遮罩层
     */
    private View bgContent;
    /**
     * 展开状态下toolbar显示的内容
     */
    private View toolbarOpen;
    /**
     * 展开状态下toolbar的遮罩层
     */
    private View bgToolbarOpen;
    /**
     * 收缩状态下toolbar显示的内容
     */
    private View toolbarClose;

    /**
     * 收缩状态下toolbar的遮罩层
     */
    private View bgToolbarClose;

    private LinearLayout llErrTip;
    private boolean isdownPull = false;//是否是下拉操作
    private LinearLayout llNoData;
    private String customerId;
    private NestedScrollView nestedScrollView;
    private final int titleMaxEms = 12;

    @Override
    public String getBaseTag() {
        return "HomeNewFragment";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.home_new_fragment,
                container, false);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        iniData();
        initView(v);
        reqMerchantList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView(View view) {
        nestedScrollView = view.findViewById(R.id.nsv);
        llNoData = view.findViewById(R.id.ll_no_data);
        llErrTip = view.findViewById(R.id.ll_err_tip);
        //llTipClose = view.findViewById(R.id.ll_tip_close);
        llMarketTitle = view.findViewById(R.id.ll_market_title);
        llTransactionTitle = view.findViewById(R.id.ll_transaction_title);
        llOnlineRetailersTitle = view.findViewById(R.id.ll_online_retailers_title);
        appBar = view.findViewById(R.id.app_bar);
        bgContent = view.findViewById(R.id.bg_content);
        toolbarOpen = view.findViewById(R.id.include_toolbar_open);
        bgToolbarOpen = view.findViewById(R.id.bg_toolbar_open);
        toolbarClose = view.findViewById(R.id.include_toolbar_close);
        bgToolbarClose = view.findViewById(R.id.bg_toolbar_close);

        appBar.addOnOffsetChangedListener(this);
        //llTipClose.setOnClickListener(this);

        tvOpenShop = view.findViewById(R.id.tv_open_shop);
        tvOpenShop.setOnClickListener(this);
        llTitle = view.findViewById(R.id.ll_title);
        llTitle.setOnClickListener(this);
        ivArrow = view.findViewById(R.id.iv_arrow);
        mRefreshLayout = view.findViewById(R.id.fragment_ptr_home_ptr_frame);
        mRefreshLayout.setEnableLoadmore(false);
        //刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 0;
                isdownPull = true;
                reqMerchantList();
            }
        });
        //加载更多
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (mOrderStoreDyns.size() == 0) {
                    mRefreshLayout.setEnableLoadmore(false);
                    return;
                }
                reqSupplyStoreDyn(pageNum + 1);
            }
        });
        tvPopBg = view.findViewById(R.id.view);
        tvTitle = view.findViewById(R.id.tv_title);
        rvTabTop = view.findViewById(R.id.rv_tab_top);
        rvTabTopSmall = view.findViewById(R.id.rv_tab_top_small);
        GridLayoutManager mLayoutManagerTop = new GridLayoutManager(getContext(), 4);
        rvTabTopSmall.setNestedScrollingEnabled(false);
        rvTabTopSmall.setLayoutManager(mLayoutManagerTop);
        homePartTopSmallAdapter = new HomePartTopSmallAdapter(getContext(), partTopList);
        homePartTopSmallAdapter.setListener(new IndexIconOnClickListener() {
            @Override
            public void onclick(String NameId) {
                switchName(NameId);
            }
        });
        rvTabTopSmall.setAdapter(homePartTopSmallAdapter);

        rvTab1 = view.findViewById(R.id.rv_tab1);
        GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 4);
        rvTab1.setNestedScrollingEnabled(false);
        rvTab1.setLayoutManager(mLayoutManager);
        homePart1Adapter = new HomePart1Adapter(getContext(), part1List);
        homePart1Adapter.setListener(new IndexIconOnClickListener() {
            @Override
            public void onclick(String NameId) {
                switchName(NameId);
            }
        });
        rvTab1.setAdapter(homePart1Adapter);

        rvTab2 = view.findViewById(R.id.rv_tab2);
        GridLayoutManager mLayoutManager2 = new GridLayoutManager(getContext(), 4);
        rvTab2.setNestedScrollingEnabled(false);
        rvTab2.setLayoutManager(mLayoutManager2);
        homePart2Adapter = new HomePart2Adapter(getContext(), part2List);
        homePart2Adapter.setListener(new IndexIconOnClickListener() {
            @Override
            public void onclick(String NameId) {
                switchName(NameId);
            }
        });
        rvTab2.setAdapter(homePart2Adapter);

        rvTab3 = view.findViewById(R.id.rv_tab3);
        GridLayoutManager mLayoutManager3 = new GridLayoutManager(getContext(), 4);
        rvTab3.setNestedScrollingEnabled(false);
        rvTab3.setLayoutManager(mLayoutManager3);
        homePart3Adapter = new HomePart3Adapter(getContext(), part3List);
        homePart3Adapter.setListener(new IndexIconOnClickListener() {
            @Override
            public void onclick(String NameId) {
                switchName(NameId);
            }
        });
        rvTab3.setAdapter(homePart3Adapter);

        rvBottom = view.findViewById(R.id.rv_bottom);
        LinearLayoutManager mLayoutManagerBottom = new LinearLayoutManager(getActivity());
        rvBottom.setLayoutManager(mLayoutManagerBottom);
        rvBottom.setNestedScrollingEnabled(false);
        homePartBottomAdapter = new HomePartBottomAdapter(getContext(), mOrderStoreDyns);
        homePartBottomAdapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (data != null && data instanceof OrderStoreDyn) {
                    onEventOrderItem((OrderStoreDyn) data);
                }
            }
        });
        rvBottom.setAdapter(homePartBottomAdapter);
        mListPop = new ListPopupWindow(getContext());
        mListPop.setAdapter(new HomeTopPopAdapter(getContext(), merChantInfoList));
        mListPop.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        mListPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        mListPop.setAnchorView(tvPopBg);
        mListPop.setModal(true);//设置是否是模式
        mListPop.setAnimationStyle(R.style.popmenu_animation); //设置弹出和隐藏的动画
        mListPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Utils.rotateArrow(ivArrow, false);
            }
        });
        mListPop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String storeId = merChantInfoList.get(position).getStoreId();
                MerChantInfo merChantInfo = BaseApplication.getInstance().getMerchant();
                if (merChantInfo != null && merChantInfo.getStoreId().equals(storeId)) {
                    mListPop.dismiss();
                    return;
                }
                //切换店铺重置缴费是否被点击的状态
                isOnclickPay = false;
                mListPop.dismiss();
                String name = merChantInfoList.get(position).getNamePlus();
                tvTitle.setText(Utils.subTitle(name, titleMaxEms));
                BaseApplication.getInstance().putMerchant(merChantInfoList.get(position));
                reqMerchantList();
            }
        });
    }

    private void topListView() {
        if (partTopList == null || partTopList.size() == 0) {
            rvTabTop.setVisibility(View.GONE);
            return;
        }
        rvTabTop.setVisibility(View.VISIBLE);
        GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), partTopList.size());
        rvTabTop.setNestedScrollingEnabled(false);
        rvTabTop.setLayoutManager(mLayoutManager);
        homePartTopAdapter = new HomePartTopAdapter(getContext(), partTopList);
        homePartTopAdapter.setListener(new IndexIconOnClickListener() {
            @Override
            public void onclick(String NameId) {
                switchName(NameId);
            }
        });
        rvTabTop.setAdapter(homePartTopAdapter);
    }

    private void iniData() {
        EventBus.getDefault().register(this);
        //预登记
        part1Permission.put(MarketPermissionUtil.marketPreRegistration, 0);
        //缴费
        part1Permission.put(MarketPermissionUtil.marketPay, 1);
        //进场登记
        part1Permission.put(MarketPermissionUtil.marketOis, 2);
        //检测报告
        part1Permission.put(MarketPermissionUtil.marketDetection, 3);
        //我的合同
        part1Permission.put(MarketPermissionUtil.marketMyDetection, 4);
        //我的车辆
        part1Permission.put(MarketPermissionUtil.marketMyCar, 5);
        //变价
        part2Permission.put(MarketPermissionUtil.appSupplierProductPrice, 6);
        //收款
        part2Permission.put(MarketPermissionUtil.appSupplierToIncome, 7);
        //销售订单
        part2Permission.put(MarketPermissionUtil.appSupplierOrder, 8);
        //现货商品
        part2Permission.put(MarketPermissionUtil.appSupplierProductSelling, 9);
        //我的收入
        part2Permission.put(MarketPermissionUtil.appSupplierIncome, 10);
        //我的台账
        part2Permission.put(MarketPermissionUtil.appSupplierProductStanding_book, 11);
        //减免退
        part2Permission.put(MarketPermissionUtil.appSupplierOrderJmt, 12);
        //员工管理
        part2Permission.put(MarketPermissionUtil.appSupplierEmployee, 13);
        //进货管理
        part2Permission.put(MarketPermissionUtil.appSupplierProductPurchase, 14);
        //客户管理
        part2Permission.put(MarketPermissionUtil.appSupplierCustomer, 15);
        //我的店铺
        part3Permission.put(MarketPermissionUtil.appSupplierStore, 16);
        //预售商品
        part3Permission.put(MarketPermissionUtil.appSupplierProductPresell, 17);
        //备货
        part3Permission.put(MarketPermissionUtil.appSupplierJointOrder, 18);
        //抢单
        part3Permission.put(MarketPermissionUtil.appSupplierProductOften_order, 19);
        //评价
        part3Permission.put(MarketPermissionUtil.appSupplierComment, 20);
        //优惠券
        part3Permission.put(MarketPermissionUtil.appSupplierCoupon, 21);
        //联营报价
        part3Permission.put(MarketPermissionUtil.appSupplierJointProduct, 22);
    }

    protected void onEventOrderItem(OrderStoreDyn osd) {
        String type = osd.getType();
        DataManager.getInstance().isNoRefreshSell = true;
        //订单
        if ("ORDER".equals(type)) {
            intoOrder(osd);
        } else if ("JMT".equals(type)) {//减免退
            intoJMT(osd);
        } else if ("COMMENT".equals(type)) {//评论
            intoComment(osd);
        } else if ("PLATFORM".equals(type)) {//台账
            intoStandBook(osd);
        }
    }

    private void updateLoadToolbarTitle(String name) {
        if (merChantInfoList.size() > 1) {
            ivArrow.setVisibility(View.VISIBLE);
        } else {
            ivArrow.setVisibility(View.GONE);
        }
        tvTitle.setText(Utils.subTitle(name, titleMaxEms));
    }

    private boolean isHavePay;

    private void updatePermission() {
        isHavePay = false;
        part1List.clear();
        part2List.clear();
        part3List.clear();
        partTopList.clear();
        MerChantInfo merChantInfo = BaseApplication.getInstance().getMerchant();
        //是否显示去开店按钮
        llErrTip.setVisibility(View.GONE);
        if (merChantInfo.getStoreStatus().equals("0") || merChantInfo.getStoreStatus().equals("3")) {
            tvOpenShop.setVisibility(View.VISIBLE);
            if (merChantInfo.getStoreStatus().equals("3")) {
                llErrTip.setVisibility(View.VISIBLE);
            }
        } else {
            tvOpenShop.setVisibility(View.GONE);
        }
        //只有管理员才能去开店
        if (!merChantInfo.isOwned()) {
            tvOpenShop.setVisibility(View.GONE);
        }
        //不是冻结状态才去遍历
        if (!merChantInfo.getStoreStatus().equals("4")) {
            Map<String, Object> map = merChantInfo.getStaffInfo().getResources();
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                if (part1Permission.containsKey(key)) {
                    HomePart homePart = new HomePart(key, part1Permission.get(key));
                    if ((Boolean) map.get(key)) {
                        partTopList.add(homePart);
                    } else {
                        part1List.add(homePart);
                    }
                    //判断是否包含缴费权限
                    if (homePart.getName().equals(MarketPermissionUtil.marketPay)) {
                        isHavePay = true;
                    }
                } else if (part2Permission.containsKey(key)) {
                    HomePart homePart = new HomePart(key, part2Permission.get(key));
                    if ((Boolean) map.get(key)) {
                        partTopList.add(homePart);
                    } else {
                        part2List.add(homePart);
                    }
                } else if (part3Permission.containsKey(key) && merChantInfo.getStoreStatus().equals("2")) {
                    HomePart homePart = new HomePart(key, part3Permission.get(key));
                    if ((Boolean) map.get(key)) {
                        partTopList.add(homePart);
                    } else {
                        part3List.add(homePart);
                    }
                }
            }
            //排序
            Collections.sort(part1List);
            Collections.sort(part2List);
            Collections.sort(part3List);
            Collections.sort(partTopList);
        }
        homePart1Adapter.setDatas(part1List);
        homePart2Adapter.setDatas(part2List);
        homePart3Adapter.setDatas(part3List);
        homePartTopSmallAdapter.setDatas(partTopList);
        if (part1List == null || part1List.size() == 0) {
            llMarketTitle.setVisibility(View.GONE);
        } else {
            llMarketTitle.setVisibility(View.VISIBLE);
        }
        if (part2List == null || part2List.size() == 0) {
            llTransactionTitle.setVisibility(View.GONE);
        } else {
            llTransactionTitle.setVisibility(View.VISIBLE);
        }
        if (part3List == null || part3List.size() == 0) {
            llOnlineRetailersTitle.setVisibility(View.GONE);
        } else {
            llOnlineRetailersTitle.setVisibility(View.VISIBLE);
        }

        //判断是否要显示暂无数据
        if (part1List.size() == 0 && part2List.size() == 0 && part3List.size() == 0 && tvOpenShop.getVisibility() == View.GONE) {
            llNoData.setVisibility(View.VISIBLE);
            nestedScrollView.setNestedScrollingEnabled(false);
            rvBottom.setVisibility(View.GONE);
        } else {
            llNoData.setVisibility(View.GONE);
            nestedScrollView.setNestedScrollingEnabled(true);
            rvBottom.setVisibility(View.VISIBLE);
        }
    }

    public void reqMerchantList() {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_account_merchant_afterLogin);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_account_merchant_afterLogin, onMerchantRequestListener);
    }

    private OnRequestListener<List<MerChantInfo>> onMerchantRequestListener = new OnRequestListener<List<MerChantInfo>>() {
        @Override
        public List<MerChantInfo> jsonToObj(String responseStr) {
            MerchantMember merchantMember = JsonUtils.fromJson(responseStr, MerchantMember.class);
            ArrayList<String> disabledResources = null;
            List<MerChantInfo> mcis = new ArrayList<MerChantInfo>();
            if (merchantMember != null && merchantMember.getEmployees() != null && merchantMember.getEmployees().size() != 0) {//
                List<StaffInfo> list = merchantMember.getEmployees();
                disabledResources = merchantMember.getDisabledResources();

                if (list != null)
                    for (int i = 0; i < list.size(); i++) {
                        StaffInfo staffInfo = list.get(i);
                        if (staffInfo != null) {
                            MerChantInfo mc = staffInfo.getMerchant();
                            if (mc != null) {
                                staffInfo.setMerchant(null);
                                mc.setStaffInfo(staffInfo);
                                if (mc.isOwned()) {
                                    mc.setDisabledResources(disabledResources);
                                }
                                mcis.add(mc);
                            }
                        }
                    }

            } else {
                BaseApplication.getInstance().putMerchant(new MerChantInfo());
            }
            BaseApplication.getInstance().updateMerchants(mcis);
            BaseApplication.getInstance().putMerchantDisabledResources(disabledResources);
            return mcis;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            if (!isdownPull)
                hideProgressDialog();
            if (mRefreshLayout != null)
                mRefreshLayout.finishRefresh();
            isdownPull = false;
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            if (!isdownPull)
                hideProgressDialog();
            if (mRefreshLayout != null)
                mRefreshLayout.finishRefresh();
            isdownPull = false;
        }

        @Override
        public void onStart(Object tag) {
            if (!isdownPull)
                showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<List<MerChantInfo>> response, Object tag) {
            if (getActivity() == null) {
                return;
            }
            hideProgressDialog();
            List<MerChantInfo> responseElement = response.getResponseElement();
            merChantInfoList.clear();
            if (responseElement != null) {
                //  merChantInfoList.addAll(responseElement);
                for (int i = 0; i < responseElement.size(); i++) {
                    if (responseElement.get(i).getStoreStatus().equals("2") || !TextUtils.isEmpty(responseElement.get(i).getSubjectCode())) {
                        merChantInfoList.add(responseElement.get(i));
                    }
                }
            }
            MerChantInfo merChantInfo = BaseApplication.getInstance().getMerchant();
            updateLoadToolbarTitle(merChantInfo.getNamePlus());
            //冻结状态不显示消息
            if (!merChantInfo.getStoreStatus().equals("4")) {
                reqSupplyStoreDyn(pageNum);
            } else {
                if (!isdownPull)
                    hideProgressDialog();
                if (mRefreshLayout != null)
                    mRefreshLayout.finishRefresh();
                isdownPull = false;
            }
            updatePermission();
            topListView();
            //判断是否有批发市场的权限
            if (part1List.size() > 0) {
                //请求批发市场的登录
                reqLoginWebToken(merChantInfo.getSubjectCode());
            }
            //更改实名信息的状态
            EventBus.getDefault().post(new MineCertStatusEvenbus());
        }
    };

    //批发市场登录用 主体码登录
    private void reqLoginWebToken(String subjectCode) {
        ApplicationHelper.urlChoose = 1;
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_auth_web_login);
        RequestEntityMapSupply.putParameter("subjectCode", subjectCode);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_auth_web_login, onWebLoginRequestListener);
    }

    private OnRequestListener<WebTokenReponse> onWebLoginRequestListener = new OnRequestListener<WebTokenReponse>() {
        @Override
        public WebTokenReponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<WebTokenReponse>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            ApplicationHelper.urlChoose = 0;
            hideProgressDialog();
            //主体码登录失败不显示市场服务模块
            hideMarketList();
            homePart1Adapter.setDatas(part1List);
            if (part1List == null || part1List.size() == 0) {
                llMarketTitle.setVisibility(View.GONE);
            } else {
                llMarketTitle.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            ApplicationHelper.urlChoose = 0;
            hideProgressDialog();
            //主体码登录失败不显示市场服务模块
            hideMarketList();
            if (part1List == null || part1List.size() == 0) {
                llMarketTitle.setVisibility(View.GONE);
            } else {
                llMarketTitle.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<WebTokenReponse> response, Object tag) {
            hideProgressDialog();
            ApplicationHelper.urlChoose = 0;
            MMKV.defaultMMKV().encode("token", response.getResponseElement().getToken());
            customerId = response.getResponseElement().getCustomerId();
            if (isHavePay)
                //去获取批发市场小红点
                webPayRedPoint();
        }
    };

    private void hideMarketList() {
        part1List.clear();
        homePart1Adapter.setDatas(part1List);
        for (int i = 0; i < partTopList.size(); i++) {
            //去除常用里面的市场服务模块
            if (partTopList.get(i).getSort() < 6) {
                partTopList.remove(i);
                i--;
            } else {
                break;
            }
        }
        homePartTopAdapter.setDatas(partTopList);
        homePartTopSmallAdapter.setDatas(partTopList);
    }

    //获取首页下面的列表
    private void reqSupplyStoreDyn(int pageNum) {
        if (getActivity() == null) {
            return;
        }
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_order_supplier_order_dyn);

       /* "storeId": "",
        "pageNumber": "1",
        "pageSize": "10"*/
        if (BaseApplication.getInstance().getStoreId() == null || BaseApplication.getInstance().getMerchantId() == null) {
            getAppActivity().toast("数据获取失败");
            finishLoad(false, false);
            mRefreshLayout.setEnableLoadmore(false);
            return;
        }
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("coId", BaseApplication.getInstance().getMerchantId());
        RequestEntityMapSupply.putParameter("pageNumber", pageNum);
        RequestEntityMapSupply.putParameter("pageSize", 15);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_order_supplier_order_dyn, onSupplyStoreDynRequestListener);
    }

    private OnRequestListener<ContentEntity<OrderStoreDyn>> onSupplyStoreDynRequestListener = new OnRequestListener<ContentEntity<OrderStoreDyn>>() {
        @Override
        public ContentEntity<OrderStoreDyn> jsonToObj(String responseStr) {
            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, OrderStoreDyn.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            finishLoad(false, false);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            finishLoad(false, false);
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<OrderStoreDyn>> response, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ContentEntity<OrderStoreDyn> responseElement = response.getResponseElement();
            last = responseElement.getLast();
            int number = responseElement.getNumber();
            List<OrderStoreDyn> content = responseElement.getContent();
            //第一页
            if (number == 0) mOrderStoreDyns.clear();
            pageNum = number;
            if (content != null) mOrderStoreDyns.addAll(content);
            if (mOrderStoreDyns.size() > 0) {
                if (!mRefreshLayout.isEnableLoadmore()) mRefreshLayout.setEnableLoadmore(true);
            } else {
                mRefreshLayout.setEnableLoadmore(false);
            }
            homePartBottomAdapter.setData(mOrderStoreDyns);
            finishLoad(true, last);
        }
    };

    /**
     * web缴费小红点
     */
    private void webPayRedPoint() {
        if (isOnclickPay) return;
        MerChantInfo merChantInfo = BaseApplication.getInstance().getMerchant();
        //存在缴费的权限才去获取是否有小红点
        if (merChantInfo != null && MarketPermissionUtil.isMarketPayPermission(merChantInfo.getStaffInfo())) {
            ApplicationHelper.urlChoose = 2;
            RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
            data.setCmd(AppSupplyRouterConstant.cmd_auth_web_receipt_list);
            //    data.setMenuCode("merchant.record");
            Map<String, String> map = new HashMap<>();
            map.put("consumerId", customerId);
            data.setParameters(map);
            request(data, AppSupplyRouterConstant.cmd_auth_web_receipt_list, webReceiptListRequestListener);
        }
    }

    private OnRequestListener<List<ReceiptReponse>> webReceiptListRequestListener = new OnRequestListener<List<ReceiptReponse>>() {
        @Override
        public List<ReceiptReponse> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<ReceiptReponse>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            ApplicationHelper.urlChoose = 0;
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            ApplicationHelper.urlChoose = 0;
            if (failCode == 401) {
                MMKV.defaultMMKV().encode("token", "");
                MMKV.defaultMMKV().encode("toIndex", -1);
            }
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<List<ReceiptReponse>> response, Object tag) {
            ApplicationHelper.urlChoose = 0;
            //是否显示小红点
            if (response.getResponseElement() != null && response.getResponseElement().size() > 0) {
                homePart1Adapter.setShowRedPoint(true);
                homePartTopAdapter.setShowRedPoint(true);
                homePartTopSmallAdapter.setShowRedPoint(true);
            } else {
                homePart1Adapter.setShowRedPoint(false);
                homePartTopAdapter.setShowRedPoint(false);
                homePartTopSmallAdapter.setShowRedPoint(false);
            }
            homePart1Adapter.setDatas(part1List);
            homePartTopAdapter.setDatas(partTopList);
            homePartTopSmallAdapter.setDatas(partTopList);
        }
    };

    private void finishLoad(boolean isSuccess, boolean isLast) {
        isdownPull = false;
        if (pageNum == 0) {
            mRefreshLayout.finishRefresh();
            if (isLast) mRefreshLayout.setEnableLoadmore(false);
        } else {
            if (isLast) {
                mRefreshLayout.finishLoadmoreWithNoMoreData();
            } else {
                mRefreshLayout.finishLoadmore(isSuccess);
            }
        }
    }

    //订单
    protected void intoOrder(OrderStoreDyn osd) {
        Intent detail = new Intent(getContext(), H5OrderDetailActivity.class);
        detail.putExtra("orderId", osd.getObjectId());
        detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_URL, "http://m.epfresh.com/help/order_supply_new.html?orderId=" + osd.getObjectId());
        detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_TITLE, "订单详情");
        startActivity(detail);
    }

    //减免退
    protected void intoJMT(OrderStoreDyn osd) {
        if (osd == null) {
            return;
        }
        Intent intent = new Intent(getAppActivity(), OrderMinusDetailActivity.class);
        intent.putExtra("id", osd.getObjectId());
        startActivity(intent);
    }

    //评论
    protected void intoComment(OrderStoreDyn osd) {
        Intent intent = new Intent(getAppActivity(), MoreEvaluateActivity.class);
        startActivity(intent);
    }

    //台账
    protected void intoStandBook(OrderStoreDyn osd) {
        Intent intent = new Intent(getAppActivity(), StandingBookActivity.class);
        startActivity(intent);
    }

    //变价/进货   暂时为商品已上架列表
    protected void intoEditPrice() {
        Intent intent = new Intent(getAppActivity(), ChangePriceActivity.class);
        startActivityForResult(intent, 0x002);
    }

    //收款
    protected void intoWriteOff() {
        Intent intent = new Intent(getAppActivity(), DebtActivity.class);
        startActivity(intent);
    }

    //销售订单
    protected void intoSaleOrder() {
        Intent intent = new Intent(getAppActivity(), OrderMoreActivity.class);
        intent.putExtra(Constant.TYPE, 5);
        startActivity(intent);
    }

    //现货商品
    protected void intoSelling() {
        Intent intent = new Intent(getAppActivity(), ProductActivity.class);
        intent.putExtra("productType", 1);
        startActivity(intent);
    }

    //我的收入
    protected void intoIncome() {
        Intent intent = new Intent(getAppActivity(), BookActivity.class);
        startActivity(intent);
    }

    //我的台帐
    protected void intoStandBook() {
        Intent intent = new Intent(getAppActivity(), StandingBookActivity.class);
        startActivity(intent);
    }

    //减免退
    protected void intoJMT() {
        Intent intent = new Intent(getAppActivity(), OrderMinusListActivity.class);
        intent.putExtra(Constant.TYPE, 3);
        startActivity(intent);
    }

    //员工管理
    protected void intoEmployee() {
        Intent intent = new Intent(getAppActivity(), EmployManageActivity.class);
        startActivity(intent);
    }

    //进货   暂时为商品已上架列表
    protected void intoStock() {
        Intent intent = new Intent(getAppActivity(), GoodsStockActivity.class);
        startActivity(intent);
    }

    //客户管理
    protected void intoCustomer() {
        Intent customer = new Intent(getAppActivity(), CustomerInfoActivity.class);
        customer.setAction(HOME_ACTIVITY);
        startActivity(customer);
    }

    //预售商品
    protected void intoPreSelling() {
        Intent intent = new Intent(getAppActivity(), ProductActivity.class);
        intent.putExtra("productType", 2);
        startActivity(intent);
    }

    //联营备货
    protected void intoJoinPrepare() {
        Intent intent = new Intent(getAppActivity(), JoinPrepareListActivity.class);
        startActivityForResult(intent, 0x002);
    }

    //抢单
    protected void intoOffer() {
        Intent intent = new Intent(getAppActivity(), OfferListActivity.class);
        startActivity(intent);
    }

    //评价
    protected void intoComment() {
        Intent intent = new Intent(getAppActivity(), MoreEvaluateActivity.class);
        startActivity(intent);
    }

    //优惠券
    protected void intoCoupon() {
        Intent coupons = new Intent(getAppActivity(), MyCouponActivity.class);
        startActivity(coupons);
    }

    //联营报价
    protected void intoJoinPrice() {
        Intent intent = new Intent(getAppActivity(), JoinPriceActivity.class);
        startActivityForResult(intent, 0x002);
    }

    //我的店铺
    protected void intoMyShop() {
        MerChantInfo merchant = BaseApplication.getInstance().getMerchant();
        String storeStatus = merchant.getStoreStatus();
        Intent intent = new Intent(getAppActivity(), StoreEnsureAndOpenActivity.class);
        intent.putExtra("cert_status", storeStatus);
        intent.putExtra("cert_type", storeStatus);
        intent.putExtra("card_count", "1");
        startActivity(intent);
    }

    //市场服务里的web页面
    protected void intoPayWeb(String name) {
        String token = MMKV.defaultMMKV().decodeString("token");
        String url = com.epfresh.api.constant.Constant.hostMobile + "/smartMerchants.html#/" + name + "?consumerId=" + customerId + "&token=" + token + "&app=android";
        Intent intent = new Intent(getAppActivity(), WXPayEntryActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("name", name);
        startActivity(intent);
    }

    public void switchName(String name) {
        switch (name) {
            case MarketPermissionUtil.marketOis:
                intoPayWeb("appRoachMain");
                break;
            case MarketPermissionUtil.marketDetection:
                intoPayWeb("reportMain");
                break;
            case MarketPermissionUtil.marketMyDetection:
                intoPayWeb("contractMain");
                break;
            case MarketPermissionUtil.marketMyCar:
                intoPayWeb("verhicleMain");
                break;
            case MarketPermissionUtil.marketPreRegistration:
                intoPayWeb("appRoachUpdate");
                break;
            case MarketPermissionUtil.marketPay:
                intoPayWeb("payMain");
                break;
            case MarketPermissionUtil.appSupplierProductPrice:
                intoEditPrice();
                break;
            case MarketPermissionUtil.appSupplierToIncome:
                intoWriteOff();
                break;
            case MarketPermissionUtil.appSupplierOrder:
                intoSaleOrder();
                break;
            case MarketPermissionUtil.appSupplierProductSelling:
                intoSelling();
                break;
            case MarketPermissionUtil.appSupplierIncome:
                intoIncome();
                break;
            case MarketPermissionUtil.appSupplierProductStanding_book:
                intoStandBook();
                break;
            case MarketPermissionUtil.appSupplierOrderJmt:
                intoJMT();
                break;
            case MarketPermissionUtil.appSupplierEmployee:
                intoEmployee();
                break;
            case MarketPermissionUtil.appSupplierProductPurchase:
                intoStock();
                break;
            case MarketPermissionUtil.appSupplierCustomer:
                intoCustomer();
                break;
            case MarketPermissionUtil.appSupplierStore:
                intoMyShop();
                break;
            case MarketPermissionUtil.appSupplierProductPresell:
                intoPreSelling();
                break;
            case MarketPermissionUtil.appSupplierJointOrder:
                intoJoinPrepare();
                break;
            case MarketPermissionUtil.appSupplierProductOften_order:
                intoOffer();
                break;
            case MarketPermissionUtil.appSupplierComment:
                intoComment();
                break;
            case MarketPermissionUtil.appSupplierCoupon:
                intoCoupon();
                break;
            case MarketPermissionUtil.appSupplierJointProduct:
                intoJoinPrice();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //头部箭头点击
            case R.id.ll_title:
                if (ivArrow.getVisibility() == View.VISIBLE) {
                    Utils.rotateArrow(ivArrow, true);
                    mListPop.show();
                }
                break;
            //开网店
            case R.id.tv_open_shop:
                Intent i = new Intent(getContext(), StoreActivity.class);
                i.putExtra(Constant.KEY_STORE_TYPE_STATUS, Constant.TYPE_STORE_STATUS_FIRST_OPEN);
                startActivity(i);
                break;
//            case R.id.ll_tip_close:
//                llErrTip.setVisibility(View.GONE);
//                break;
        }
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        Utils.topSlidingEffect(appBarLayout, verticalOffset, toolbarOpen, toolbarClose, bgToolbarOpen, bgToolbarClose, bgContent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void homeNewEvenbus(HomeNewEvenbus event) {
        isOnclickPay = true;
        homePart1Adapter.setShowRedPoint(false);
        homePartTopAdapter.setShowRedPoint(false);
        homePartTopSmallAdapter.setShowRedPoint(false);
        homePart1Adapter.setDatas(part1List);
        homePartTopAdapter.setDatas(partTopList);
        homePartTopSmallAdapter.setDatas(partTopList);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void homeNewUpadteEvenbus(HomeNewUpadteEvenbus event) {
        reqMerchantList();
    }
}

